<template>
  <div id="box">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <h2>登录</h2>
      <br />
      <el-form-item label="用户名" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-button type="info" round @click="login">登录</el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        name: "admin",
        password: "123456",
      },
      rules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
      },
    };
  },

  mounted() {},

  methods: {
    login() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          this.$message({
            message: "格式有错误",
            type: "warning",
          });
          return false;
        } else {
          console.log(this.ruleForm);
          this.$axios
            .post("/login", {
              username: this.ruleForm.name,
              password: this.ruleForm.password,
            })
            .then((res) => {
              console.log(res.data.data);
              if (res.data.meta.status == 200) {
                this.$message({
                  message: "登陆成功",
                  type: "success",
                });
                this.$store.commit("userinfo", res.data.data);
                this.$router.push({
                  path: "/",
                });
              } else {
                this.$message({
                  message: res.data.meta.msg,
                  type: "warning",
                });
              }
            });
        }
      });
    },
  },
};
</script>

<style lang="css">
* {
  margin: 0;
  padding: 0;
}
#box {
  width: 500px;
  margin: 0 auto;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>